/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.lottery.game.core.modules.service.app;

import com.lottery.game.common.constants.GameConstants;
import com.lottery.game.common.exception.BaseException;
import com.lottery.game.common.utils.MD5Util;
import com.lottery.game.common.utils.MakeNoUtil;
import com.lottery.game.common.utils.UUIDUtils;
import com.lottery.game.common.utils.ValidateUtils;
import com.lottery.game.core.modules.entity.user.GameUser;
import com.lottery.game.core.modules.mapper.GameUserDao;
import com.lottery.game.core.modules.mapper.UserLoginDao;
import com.lottery.game.core.modules.service.redis.RedisService;
import com.lottery.game.core.utils.HexUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpSession;

/**
 * 游戏用户Service
 * @author chenye
 * @version 2018-03-25
 */
@Service
//@Transactional(readOnly = true)
@Transactional
public class GameUserService {

	@Autowired
	private GameUserDao gameUserDao;

	@Autowired
	private RedisService redisService;

	@Autowired
	private UserLoginDao userLoginDao;

	public Map<String,Object> getGameUserListdata(Map<String,Object> map) {
		return this.gameUserDao.getGameUserListdata(map);
	}

	public GameUser getGameUserByUserName(String phone) {
        return this.gameUserDao.getGameUserByUserName(phone);
    }

	public GameUser get(String id){
		return this.gameUserDao.get(id);
	}

	public Map<String, String> validate_register(
			String username,
			String password,
			String phone,
			String phoneCode,
			String qq,
			String introducer,
			HttpSession session, String address) throws Exception {
		Map<String, String> map = new HashMap<String, String>();

		if ("".equals(username) || username == null) {
			map.put("message", "用户名不能为空");
			map.put("status", "fail");
			return map;
		}
		// 判断用户名是否正确  //4-18字母的组合，最少一个字母
		//
		if(ValidateUtils.isNum(username)){
			map.put("message", "用户名应为4到18为大写字母，小写字母，数字的组合！");
			map.put("status", "fail");
			return map;
		}
		GameUser gameUser = this.gameUserDao.getGameUserByUserName(username);
		int robotCount = this.gameUserDao.queryRobotManageCountByName(username);
		//判断用户名是否被其他用户或者机器人占用
		if (gameUser != null && robotCount == 0) {
			map.put("message", "用户名已存在！");
			map.put("status", "fail");
			return map;
		}

		if (password.length() < 6 || password.length() > 18) {
			map.put("message", "密码长度应为6到18位");
			map.put("status", "fail");
			return map;
		}
		if (!ValidateUtils.isNull(phone)) {
			map.put("message", "手机号不能为空！");
			map.put("status", "fail");
			return map;
		}
		if (!ValidateUtils.isNull(phoneCode)) {
			map.put("message", "验证码不能为空！");
			map.put("status", "fail");
			return map;
		}
		if (!ValidateUtils.isCode(phoneCode)) {
			map.put("message", "验证码格式错误！");
			map.put("status", "fail");
			return map;
		}
		// 判断手机验号是否正确
		if (!ValidateUtils.isMobile(phone)) {
			map.put("message", "手机号格式错误！");
			map.put("status", "fail");
			return map;
		}
		String phone_code = this.redisService.get(phone);
		if (phone_code == null || !(phone_code.toString().equals(phoneCode))) {
			// 验证码错误
			map.put("message", "手机验证码错误！");
			map.put("status", "fail");
			return map;
		}
		// 查询用户是否存在
		Integer b = this.gameUserDao.queryUserCount(username, phone);
		if (b != null && b.longValue() > 0) {
			// 用户名、手机、电子邮件存在
			map.put("message", "手机号已经存在！");
			map.put("status", "fail");
			return map;
		}
		//盐。 随机生成
		String salt = UUIDUtils.randomUUID();
		//生成订单号
		String no = MakeNoUtil.makeOrderNum();
		//密码加盐
		String pwd = MD5Util.MD532(MD5Util.MD532(password), salt);
		Date registeDate = new Date();

		GameUser user = new GameUser(UUIDUtils.randomUUID(), username, pwd, phone, no, salt, qq, introducer, address, registeDate);
		//根据推荐码 查找上级用户
		String superiors = null;
		if (!StringUtils.isEmpty(introducer)) {
			Integer UserNo = HexUtil.parseInt(introducer);
			superiors = this.gameUserDao.queryUserIdByNo(String.valueOf(UserNo));
			user.setSuperiors(superiors);
			user.setAgent_date(registeDate);
		}
		//user.setRegister_ip_area(address);//添加注册ip地区
		//配置随机头像
		Random random = new Random();
		String defaultPhoto = String.format(GameConstants.DEFAULT_USER_PHOTO_PARSE,random.nextInt(10));
		user.setPhotourl(defaultPhoto);
		int num = this.gameUserDao.insertUser(user);
		if (num >= 1) {
			map.put("message", "注册成功!");
			map.put("status", "success");
		}
		return map;
	}

	public boolean register(GameUser user, String introducer) {
		if (!StringUtils.isEmpty(introducer)) {
			Integer userNo = HexUtil.parseInt(introducer);
			user.setSuperiors(this.gameUserDao.queryUserIdByNo(String.valueOf(userNo)));
			//用户初始验证密码
			user.setPayment_assword("123456");
			user.setAgent_date(new Date());
		}
		return this.gameUserDao.insertUser(user) > 0;
	}

	/**
	 * 修改用户登陆密码验证旧密码
	 * @param userId
	 * @param username
	 * @param userPwd
	 * @param oldPwd
	 * @return
	 */
	public Integer updatePwd(String userId,String username,String userPwd,String oldPwd) {
		Map<String, String> paramMap=new HashMap<>();

		String salt = this.userLoginDao.getSaltByUsername(username);//根据用户名去获取盐
		String newUserPwd=MD5Util.MD532(MD5Util.MD532(userPwd), salt);//加密
		Map<String, Object> userMapPam = new HashMap<>();

		String oldUserPwd = MD5Util.MD532(MD5Util.MD532(oldPwd), salt);

		userMapPam.put("userId", userId);
		userMapPam.put("oldUserPwd", oldUserPwd);
		Map<String, Object> userMap = this.gameUserDao.getGameUserpwd(userMapPam);
		//判断用户是否存在
		if(userMap!=null) {
			paramMap.put("userId", userId);
			paramMap.put("newUserPwd", newUserPwd);
			int num = this.gameUserDao.updatePwd(paramMap);
			if(num>0) {
				return 0;
			}else {
				return 1;
			}
		}else {
			return -1;
		}
	}

	/**
	 * 修改密码不需要验证旧密码
	 * @param username
	 * @return
	 */
	public Map<String, Object> updateNewPwd(String phoneNumber,String username,String userPwd){
		Map<String, Object> map=new HashMap<String, Object>();
		Map<String, String> paramMap=new HashMap<>();
		String salt = this.gameUserDao.getSaltByUsername(username);//根据用户名去获取盐
		String pwd=MD5Util.MD532(MD5Util.MD532(userPwd), salt);//加密
		//判断用户是否存在
		paramMap.put("phoneNumber", phoneNumber);
		paramMap.put("userPwd", pwd);
		int num = this.gameUserDao.updateNewPwd(paramMap);
		if(num>0) {
			map.put("message", "修改密码成功!");
			map.put("status", "success");
			map.put("code", "200");
		}else {
			map.put("message", "修改密码失败!");
			map.put("status", "fail");
			map.put("code", "500");
		}
		return map;
	}

	/**
	 * 修改支付密码验证旧密码
	 * @param userId
	 * @param username
	 * @param userPayPwd
	 * @param oldPayPwd
	 * @return
	 */
	public Integer updatePayPwd(String userId,String username,String userPayPwd,String oldPayPwd) {
		Map<String, String> paramMap = new HashMap<>();
		String salt = this.userLoginDao.getSaltByUsername(username);//根据用户名去获取盐
		//设置新密码
		String payPwd = MD5Util.MD532(MD5Util.MD532(userPayPwd), salt);
		String oldPayPwdInfo = MD5Util.MD532(MD5Util.MD532(oldPayPwd), salt);
		Map<String, Object> userMapPam = new HashMap<>();
		userMapPam.put("userId", userId);
		userMapPam.put("oldPayPwdInfo", oldPayPwdInfo);
		Map<String, Object> userMap = this.gameUserDao.getGameUserPayPwd(userMapPam);
		if(userMap!=null) {
			paramMap.put("userId", userId);
			paramMap.put("payPwd", payPwd);
			int num = this.gameUserDao.updatePayPwd(paramMap);
			if(num > 0) {
				return 0;
			} else {
				return 1;
			}
		}else {
			return -1;
		}
	}

	/**
	 * 修改支付密码不需要验证
	 * @param userId
	 * @param username
	 * @param userPayPwd
	 * @return
	 */
	public Boolean updateNewPayPwd(String userId,String username,String userPayPwd){
		Map<String, String> paramMap = new HashMap<>();
		String salt = this.userLoginDao.getSaltByUsername(username);//根据用户名去获取盐
		String payPwd=MD5Util.MD532(MD5Util.MD532(userPayPwd), salt);
		paramMap.put("userId", userId);
		paramMap.put("payPwd", payPwd);
		int num = this.gameUserDao.updatePayPwd(paramMap);

		return (num > 0);
	}

	/**
	 * 修改头像地址
	 * @param userId
	 * @param uploadPath
	 * @return
	 */
	public int updatePhotoAddress(String userId, String uploadPath) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", userId);
		map.put("uploadPath", uploadPath);
		return this.gameUserDao.updatePhotoAddress(map);
	}

	/**
	 * 很久之前phone和用户名搞混了
	 * @param phone
	 * @return
	 */
	public boolean checkPhone(String phone) {
		return this.checkUserName(phone);
	}

	public Boolean checkUserName(String username) {
			Boolean result = true;
	    GameUser gameUser = this.gameUserDao.getGameUserByUserName(username);
			int robotCount = this.gameUserDao.queryRobotManageCountByName(username);
			if (robotCount > 0 || gameUser != null) {
				result = false;
			}
	    return result;
	}

	public void updateGameBalance(GameUser gameUser){
		this.gameUserDao.updateGameBalance(gameUser);
	}

	public int updateUserOnlineStatus(String userOnlineStatus ,String userId) {

		Map<String, String> map = new HashMap<>();
		map.put("userOnlineStatus", userOnlineStatus);
		map.put("userId", userId);
		return this.gameUserDao.updateUserOnlineStatus(map);
	}

	public int updateBatchUserOnlineStatus(List<Map<String, Object>> list) {
		return this.gameUserDao.updateBatchUserOnlineStatus(list);
	}

	//验证支付密码
	public Boolean regNewPayPwd(String userId,String userName,String userPayPwd){
		Map<String, Object> reulsMap=new HashMap<>();
		Map<String, String> paramMap=new HashMap<>();
		//根据用户名去获取盐
		String salt = this.userLoginDao.getSaltByUsername(userName);
		String payPwd=MD5Util.MD532(MD5Util.MD532(userPayPwd), salt);
		paramMap.put("userId", userId);
		paramMap.put("userPayPwd", payPwd);
		Map<String, Object> map = this.gameUserDao.regNewPayPwd(paramMap);

		return (map != null);


	}

}
